package com.jt.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration //配置类标识
@PropertySource("classpath:/properties/redis.properties")
public class JedisConfig {

    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private Integer port;
    @Value("${redis.nodes}")
    private String nodes;
    @Value("${redis.clusters}")
    private String clusters;
    /**
     * 将jedis兑现交给spring容器管理
     */
    @Bean //默认条件下是单例模式
    public Jedis jedis(){
        return new Jedis(host,port);
    }

    @Bean
    public ShardedJedis shardedJedis(){
        List<JedisShardInfo> list = new ArrayList<>();
        String[] array = nodes.split(",");
        for(String node:array){
            String host = node.split(":")[0];
            int port = Integer.parseInt(node.split(":")[1]);
            JedisShardInfo jedisShardInfo = new JedisShardInfo(host,port);
            list.add(jedisShardInfo);
        }
        return new ShardedJedis(list);
    }

    @Bean
    public JedisCluster jedisCluster(){
        Set<HostAndPort> set = new HashSet<>();
        String[] array = clusters.split(",");
        for(String cluster : array){
            String host = cluster.split(":")[0];
            int port = Integer.parseInt(cluster.split(":")[1]);
            set.add(new HostAndPort(host,port));
        }
        return new JedisCluster(set);
    }
}
